package com.ruoyi.insect.utils;

import com.drew.imaging.ImageMetadataReader;
import com.drew.metadata.Metadata;
import com.drew.metadata.exif.GpsDirectory;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

/**
 * GPS信息提取工具类
 */
public class GpsExtractor {

    /**
     * 从图片中提取GPS信息
     */
    public static GpsInfo extractGpsInfo(MultipartFile file) {
        try (InputStream inputStream = file.getInputStream()) {
            Metadata metadata = ImageMetadataReader.readMetadata(inputStream);
            GpsDirectory gpsDirectory = metadata.getFirstDirectoryOfType(GpsDirectory.class);

            if (gpsDirectory != null) {
                GpsInfo gpsInfo = new GpsInfo();

                // 提取经纬度
                if (gpsDirectory.getGeoLocation() != null) {
                    gpsInfo.setLongitude(gpsDirectory.getGeoLocation().getLongitude());
                    gpsInfo.setLatitude(gpsDirectory.getGeoLocation().getLatitude());
                }

                return gpsInfo;
            }
        } catch (Exception e) {
            // 如果提取失败，返回null，让前端传入GPS信息
            System.out.println("提取GPS信息失败: " + e.getMessage());
        }
        return null;
    }
}
